package bmatch.tech.todo.resource;

import bmatch.tech.todo.auth.TokenNeeded;
import bmatch.tech.todo.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

/**
 * @program:todo
 * @author:LinJinhao
 * @create:2019-01-02 21:30
 **/

@TokenNeeded
@Priority(Priorities.AUTHENTICATION)
public class TokenNeededFilter implements ContainerRequestFilter {
	private static final Logger logger = LoggerFactory.getLogger(TokenNeededFilter.class);

	@Override
	public void filter(ContainerRequestContext requestContext){
		//从header取token信息
		String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
		//从cookie取token信息
		if (authorizationHeader == null){
			authorizationHeader = requestContext.getCookies().get("sid").getValue();
		}
		if (StringUtils.isBlank(authorizationHeader)){
			requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
			return;
		}
		String token = authorizationHeader.substring("Bearer".length()).trim();
		try {
			String id = JwtUtils.parse(token);
			requestContext.getHeaders().add("sid",id);
		}catch (Exception e){
			logger.error("",e);
			requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
		}
	}

}
